//model层 mongoose操作数据库

//引入model模型，一切数据库操作，都基于这个模型
const createModel = require('../mongodb/createModel')

//创建Schame对象（这里是一个学生、用户对象）
const stuSchema = {
  name: String,
  age: Number,
  gender:{
    type: String,
    default:'male' //定义默认类型
  },
  addr: String,
  timestamps: {
    type: Date,
    default: Date.now
  }
}

//'students'是表名，集合名称。至此，创建模型成功后，才可以调用增删改查方法操作数据库（create，deleteOne，update…）
const stuModel = createModel('students', stuSchema)

//增
const handleAdd = (name, age) => {
  return new Promise((resolve, reject) => {
    //create()方法，添加数据
    //数据库返回状态和数据到controller层，（用async,await,处理异步）。
    //然后controller层根据服务器返回的信息，判断，返回给前端
    stuModel.create({name, age}, (err, docs) => {
      if(!err) {
        console.log('添加数据成功', docs)
        resolve({
          status: 1,
          ...docs._doc
        })
      }else{
        reject({
          status: 0
        })
        throw err
      }
    })
  })
}

//删
const handleDel = (id) => {
  return new Promise((resolve, reject) => {
    stuModel.deleteOne({_id:id}, (err) => {
      if(!err){
        console.log('删除成功')
        resolve({
          status: 1
        })
      }else{
        reject({
          status: 0
        })
        throw err
      }
    })
  })
}

//改
const handleUpdate = (id, name, age) => {
  return new Promise((resolve, reject) => {
    stuModel.updateOne({_id:id}, {name, age}, (err, docs) => {
      if(!err){
        console.log('修改成功', docs) 
        resolve({
          status: 1
        })
      }else{
        reject({
          status: 0
        })
        throw err
      }
    })
  })
}

//查
const handleFind = (name) => {
  return new Promise((resolve, reject) => {
    stuModel.find({name}, (err, docs) => {
      if(!err){
        console.log('查询成功', docs)
        resolve({
          status: 1,
          ...docs
        })
      }else{
        reject({
          status: 0
        })
        throw err
      }
    })
  })
}

module.exports = {
  handleAdd,
  handleDel,
  handleUpdate,
  handleFind
}

